<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 15-9-24
 * Time: 下午3:20
 */

class UserModel extends BaseModel{
    private $_table;
    protected $_name = 'users';
    protected $_isbug = false;

    const LOGIN_ITEM_EMAIL          = 'E';
    const LOGIN_ITEM_MOBILE         = 'M';
    const LOGIN_ITEM_NICKNAME       = 'N';

    /**
     * 根据用户名称读出对应的用户信息。
     * @param $value
     * @return array
     */
    public function getUserByLoginItem($value) {
        $condition  = array();
        switch(self::getLoginItemType($value)) {
            case self::LOGIN_ITEM_EMAIL :
                $condition  = array('email'=>$value);
                break;
            case self::LOGIN_ITEM_MOBILE :
                $condition  = array('moblie'=>$value);
                break;
            case self::LOGIN_ITEM_NICKNAME :
                $condition  = array('login_name'=>$value);
                break;
        }
        if(empty($condition)){
            $condition = array('moblie'=>$value);
        }
        foreach($condition as $key=>$val){
            $row = $key;
            $content = $val;
        }
        $user_info  = self::getlineByRow($row, $content);
        return $user_info;
    }



    /**
     * 判断登录的名称类型
     * @param $value
     * @return bool|string
     */
    public function getLoginItemType($value) {
        $login_item_value   = trim($value);

        if( Validate::isEmail($login_item_value) ) {
            return self::LOGIN_ITEM_EMAIL;
        }
        if( Validate::isMobilePhone($login_item_value) ) {
            return self::LOGIN_ITEM_MOBILE;
        }
        if( self::isNickname($login_item_value) ) {
            return self::LOGIN_ITEM_NICKNAME;
        }
        return false;
    }

    /**
     * 判断是否字符串
     * @param $str
     * @return bool
     */
    protected static function isNickname($str) {
        if( strlen($str) < 4 ) {
            return false;
        }
        $length = mb_strlen($str, 'utf8');
        if( $length < self::$_nicknameLengthRange['min'] || $length > self::$_nicknameLengthRange['max'] ) {
            return false;
        }
        if( !preg_match('/^[a-zA-Z0-9_\x80-\xff]+$/', $str) ) {
            return false;
        }
        return true;
    }

//求购查询用户
    public function searchquote($user_info,$inquiry_id){
        if(empty($inquiry_id)) return;

        return $this->_db_handler->fetchAll("SELECT * FROM `iq_quotation` WHERE user_id={$user_info['id']} and business_id='{$user_info['invoice_id']}' and inquiry_id='{$inquiry_id}' and status <> '5'");
    }

    public function searchinquire($user_info,$inquiry_id){
        if(empty($inquiry_id)) return;

        return $this->_db_handler->fetchOne("SELECT `id` FROM `iq_inquiry` WHERE user_id={$user_info['id']}  and id='{$inquiry_id}'");
    }

    /**、
     * 获取用户信息及开票信息
     * @return array
     */
    public function UserInfo($userid){
        return $this->_db_handler->fetchRow("SELECT u.id,ui.id as invoice_id,  u.login_item, u.user_type, u.user_source, u.user_level, u.email, u.password, u.realname, u.login_name, u.sex, u.moblie, u.qq, u.province_id, u.city_id, u.area_id, u.detail_addr, u.zip, u.tel, u.birthday, u.marriage_status, u.work_type, u.industry, u.month_income, u.reg_date, u.reg_ip, u.worker_id, u.is_audit, u.is_join, ui.title, ui.business_name, ui.business_remarks, ui.business_phone, ui.business_fax, ui.business_province_id, ui.business_city_id, ui.business_area_id, ui.business_addr, ui.certificate, ui.content_type, ui.name, ui.address, ui.phone, ui.blank_number, ui.register_addr, ui.register_phone, ui.open_blank, ui.blank_number
        , ui.business_name, ui.contacts, ui.email as shop_email,ui.mobile,u.qq as QQ , ui.qq, u. mobile_verify, u.email_verify FROM `users`  u
        left join users_invoice as ui on(u.id = ui.user_id)    WHERE u.`id` = {$userid}");
    }


    public function add($data) {
        $this->_table = new self ();
        $db = $this->_table->getAdapter ();

        $db->insert( $this->_name, $data );
        return $productId = $this->_db->lastInsertId($this->_name);
    }

    /**
     * 最大最小字符
     * @var array
     */
    private static $_nicknameLengthRange   = array(
        'min'   => 2,
        'max'   => 20
    );
    private static $_passwordLengthRange   = array(
        'min'   => 6,
        'max'   => 16
    );
    ##################################################
    /**
     * 发布保存报价
     * @param $quotation_data
     * @return bool|null
     */
    public function savebatchquote($quotation_data){
        $this->_table = new self();
        $db = $this->_table->getAdapter();
        $db->beginTransaction();
        try {
            if(empty($quotation_data)){
                return null;
            }
            foreach($quotation_data as $k=>$v){
                //这边查询报价数据中是否有重复的，有的就修改，没有的就插入
                $quote = new QuotationModel();
                $quotelist = $quote->getDetailsById("iq_quotation.user_id = '{$v['user_id']}' and iq_quotation.business_id = '{$v['business_id']}' and iq_quotation.product_id = '{$v['product_id']}' and iq_quotation.service_id = '{$v['service_id']}' and iq_quotation.currency_id = '{$v['currency_id']}' and iq_quotation.delivery_time = '{$v['delivery_time']}' and iq_quotation.area_id = '{$v['area_id']}' and iq_quotation.status <> '4'");

                if(!empty($quotelist)){
                    //这边就是只更新数据
                    $quote_data = array(
                        'update_time'=>date("Y-m-d H:i:s",strtotime('now')),
                        'update_uid'=>$v['user_id'],
                        'price'=>$v['price'],
                        'status'=>'1',
                        'num'=>$v['num'],
                        'remark'=>'批量报价，重复数据进行更新',
                    );
                    $res = $db ->update("iq_quotation",$quote_data,"id = '{$quotelist['id']}'");
                }else{
                    $res =  $db->insert("iq_quotation",$quotation_data[$k]);
                }
                //这边更新user_invoice 中 quotation_update_time
                $db->update("users_invoice",array("quotation_update_time"=>date("Y-m-d H:i:s",strtotime('now'))),"id = '{$v['business_id']}'");
            }

            $db->commit();
            return true;
        }catch (Exception $e){
            $db->rollBack();
            echo $e->getMessage();
        }
    }

    public function savequote($quotation_data){
        $this->_table = new self();
        $db = $this->_table->getAdapter();
        $db->beginTransaction();
        try {
            if(empty($quotation_data)){
                return null;
            }
            $res =  $db->insert("iq_quotation",$quotation_data);
            $db->update("users_invoice",array("quotation_update_time"=>date("Y-m-d H:i:s",strtotime('now'))),"id = '{$quotation_data['business_id']}'");
            $db->commit();
            return true;
        }catch (Exception $e){
            $db->rollBack();
            echo $e->getMessage();
        }
    }

    /**
     * @param $quotation_data
     * @param $quote_id
     * @return int|null
     */
    public function saveeditquote($quotation_data,$quote_id){
        $this->_table = new self();
        $db = $this->_table->getAdapter();
        if(empty($quotation_data)){
            return null;
        }
        return $db->update("iq_quotation",$quotation_data,"id = '{$quote_id}'");
    }
    //刷新报价信息

    public function setquoteupdate($data,$where){
        $this->_table = new self();
        $db = $this->_table->getAdapter();
        return $db->update("iq_quotation",$data,$where);
    }

    public function getquoteByuserId($id){
        $this->_table = new self ();
        $db = $this->_table->getAdapter ();
        $sql = $db->select ()->from ("iq_quotation",'*' )
            ->where("user_id = '{$id}'")->__toString ();
        if ($this->_isbug == true) {
            echo  __METHOD__.": ".$sql . "<hr/>";
        }
        $data = $db->fetchRow( $sql );
        return $data;
    }

    public function saveinquire($inquiry_data){
        $this->_table = new self();
        $db = $this->_table->getAdapter();
        $db->beginTransaction();
        try {
            if(empty($inquiry_data)){
                return null;
            }
            $res =  $db->insert("iq_inquiry",$inquiry_data);
            $db->commit();
            return true;
        }catch (Exception $e){
            $db->rollBack();
            echo $e->getMessage();
        }
    }
    //更新求购
    public function saveeditinquire($inquire_data,$inquire_id){
        $this->_table = new self();
        $db = $this->_table->getAdapter();
        if(empty($inquire_data)){
            return null;
        }
        return $db->update("iq_inquiry",$inquire_data,"id = '{$inquire_id}'");
    }

    //获取到用户的公司
    public function getUserSinvoiceByUid($userid){
        $this->_table = new self ();
        $db = $this->_table->getAdapter ();
        $sql = $db->select ()->from ("users_invoice",array("id","business_name","is_default"))->where ( "user_id='{$userid}'" )->__toString ();
        if ($this->_isbug == true) {
            echo  __METHOD__.": ".$sql . "<hr/>";
        }
        return $db->fetchAll( $sql );
    }

    //根据公司的id获取到公司信息
    //获取到用户的公司
    public function getUserSinvoiceByid($id){
        $this->_table = new self ();
        $db = $this->_table->getAdapter ();
        $sql = $db->select ()->from ("users_invoice")
            ->where ( "id='{$id}'" )
            ->__toString ();
        if ($this->_isbug == true) {
            echo  __METHOD__.": ".$sql . "<hr/>";
        }
        return $db->fetchRow( $sql );
    }
    //更新公司信息
    public function updateInvoiceById($id, $field)
    {
        $this->_table = new self ();
        $db = $this->_table->getAdapter();
        return $db->update("users_invoice", $field, "id= {$id}");
    }
    public function isExistByRow($row, $content) {
        $this->_table = new self ();
        $db = $this->_table->getAdapter ();
        $sql = $db->select ()->from ("users", $row )->where ( "`{$row}`='{$content}'" )->__toString ();
        if ($this->_isbug == true) {
            echo  __METHOD__.": ".$sql . "<hr/>";
        }
        return $db->fetchOne ( $sql );
    }
    public function isExistBusinessByRow($row, $content) {
        $this->_table = new self ();
        $db = $this->_table->getAdapter ();
        $sql = $db->select ()->from ("users_invoice", $row )->where ( "`{$row}`='{$content}'" )->__toString ();
        if ($this->_isbug == true) {
            echo  __METHOD__.": ".$sql . "<hr/>";
        }
        return $db->fetchOne ( $sql );
    }
    public function getArea($id){
        $this->_table = new self ();
        $db = $this->_table->getAdapter ();
        $sql = $db->select ()->from ("users_invoice",array("business_province_id","business_city_id","business_area_id"))
            ->joinLeft("region as province","users_invoice.business_province_id=province.region_id","region_name as province_name")
            ->joinLeft("region as city","users_invoice.business_city_id=city.region_id","region_name as city_name")
            ->joinLeft("region as area","users_invoice.business_area_id=area.region_id","region_name as area_name")
            ->where ( "id='{$id}'" )
            ->__toString ();
        if ($this->_isbug == true) {
            echo  __METHOD__.": ".$sql . "<hr/>";
        }
        return $db->fetchRow( $sql );
    }
    //根据id更新单条数据
    public function updateById($id, $field)
    {
        $this->_table = new self ();
        $db = $this->_table->getAdapter();
        return $db->update("users", $field, "id= {$id}");
    }
    //这边查询会员中心首页信息
    /**
     * @param $where
     * @return array
     */
    public function getUserInfoByWhere($where,$limit = 0){
        $this->_table = new self ();
        $db = $this->_table->getAdapter ();
        $sql = $db->select ()->from ("users")->joinLeft("users_invoice","users.id = users_invoice.user_id",array("business_name","contacts","mobile"))
            ->where ($where)->order("id asc")->__toString ();

        if(!empty($limit)){
            $sql.=" limit 1";
        }
        if ($this->_isbug == true) {
            echo  __METHOD__.": ".$sql . "<hr/>";
        }
        return $db->fetchRow( $sql );
    }

    /**
     * @param $data
     * @param $order_sku_id
     * @param $order_id
     * @return bool
     */
    public function editsaleorder($data,$order_sku_id,$order_id){
        $this->_table = new self ();
        $db = $this->_table->getAdapter();
        $db->beginTransaction();
        try {
            $db->update("sale_order_sku", $data, "id= {$order_sku_id}");
            $db->update("sale_order", array("remark"=>"商家修改订单"), "id= {$order_id}");
            $db->commit();
            return true;
        }catch (Exception $e){
            $db->rollBack();
            echo $e->getMessage();
        }

    }

    /**
     * @param $status
     * @param $order_id
     * @return bool
     */
    public function setOrderStatus($status,$order_id){
        $this->_table = new self ();
        $db = $this->_table->getAdapter();
        $db->beginTransaction();
        try {
            $db->update("sale_order", array("status"=>$status), "id= {$order_id}");
            $db->commit();
            return true;
        }catch (Exception $e){
            $db->rollBack();
            echo $e->getMessage();
        }
    }

    /**
     * @param $id
     * @return array
     */
    public function getOrderInfoById($id){
        $this->_table = new self ();
        $db = $this->_table->getAdapter ();
        $sql = $db->select ()->from ( "sale_order", "" )
            ->joinLeft ( "sale_order_sku", "sale_order_sku.order_id = sale_order.id", array ("num","price","amount","buy_sku_id" ) )
            ->joinLeft("iq_quotation","iq_quotation.id = sale_order_sku.buy_sku_id","num as quote_num")
            ->__toString();
        if ($this->_isbug == true) {
            echo __METHOD__ . ": " . $sql . "<hr/>";
        }
        return $db->fetchRow( $sql );
    }
}